package cn.gson.crm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.gson.crm.model.dao.AttachmentDao;
import cn.gson.crm.model.dao.DemandDao;
import cn.gson.crm.model.entity.Attachment;
import cn.gson.crm.model.entity.Demand;
import cn.gson.crm.service.UploadService;

@Controller
@RequestMapping("file")
public class UploadController {
	
	@Autowired
	UploadService uploadService;
	
	@Autowired
	AttachmentDao attDao;
	
	@Autowired
	DemandDao demandDao;
	
	/**
	 * 文件上传配置
	 * @param f
	 * @param id
	 * @return
	 */
	@RequestMapping("upload")
	@ResponseBody
	@PostMapping
	public Result upload(@RequestParam(value = "upload_file", required = false) CommonsMultipartFile f,Long id) {
		Attachment att;
		try {
			att = uploadService.save(f);
			return new Result(true,"","att/" + att.getFilePath(),att);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,e.getMessage(),"");
		}
		
	}
	
	
	/**
	 * 上传所需的
	 * @param request
	 * @param response
	 */
	@GetMapping("/att/**")
	public void view(HttpServletRequest request,HttpServletResponse response) {
		File file = uploadService.get(request.getServletPath().replaceFirst("/att/", ""));
	
		try {
			FileInputStream fis = new FileInputStream(file);
			ServletOutputStream os = response.getOutputStream();
		
			byte[] b = new byte[1024];
			int len = 0;
			while((len = fis.read(b)) > 0) {
				os.write(b,0,len);
			}
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * 附件下载
	 * @param fid
	 * @param request
	 * @param response
	 */
	@GetMapping("download/{fid}")
	public void download(@PathVariable("fid") Long fid,HttpServletRequest request, HttpServletResponse response) {
		Attachment att = attDao.findOne(fid);
		if (att != null) {
			File file = uploadService.get(att.getFilePath());
			
			try {
				response.reset();
				response.setContentType(att.getContentType());
				response.setContentLengthLong(att.getFileSize());
				response.setHeader("Content-Disposition", "attachment;filename=" + new String(att.getFileName().getBytes("UTF-8"), "ISO-8859-1"));
				FileInputStream fis = new FileInputStream(file);
				ServletOutputStream os = response.getOutputStream();

				byte[] b = new byte[1024];
				int len = 0;
				while ((len = fis.read(b)) > 0) {
					os.write(b, 0, len);
				}
				fis.close();

			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				response.sendError(404);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/*@RequestMapping("delete/{did}/{fid}")
	public void delete(@PathVariable("did")Long did,@PathVariable("fid")Long fid) {
		if (fid != null && did != null) {
			Demand demand = demandDao.findOne(did);
			List<Attachment> atts = demand.getAttachment();
			
			Attachment att = attDao.findOne(fid);
			
			for (int i = 0; i < atts.size(); i++) {
				if (atts.get(i) == att) {
					atts.remove(i);
					demand.setAttachment(atts);
					demandDao.save(demand);
				}
			}
			
			
		}		
	}*/
	
	
	class Result {
		boolean success = false;
		String msg;
		String file_path;
		Attachment att;

		public Result() {
		}

		public boolean isSuccess() {
			return success;
		}

		public void setSuccess(boolean success) {
			this.success = success;
		}

		public String getMsg() {
			return msg;
		}

		public void setMsg(String msg) {
			this.msg = msg;
		}

		public String getFile_path() {
			return file_path;
		}

		public void setFile_path(String file_path) {
			this.file_path = file_path;
		}

		public void setAtt(Attachment att) {
			this.att = att;
		}

		public Attachment getAtt() {
			return att;
		}

		public Result(boolean success, String msg, String file_path, Attachment att) {
			super();
			this.success = success;
			this.msg = msg;
			this.file_path = file_path;
			this.att = att;
		}

		public Result(boolean success, String msg, String file_path) {
			super();
			this.success = success;
			this.msg = msg;
			this.file_path = file_path;
		}
	}
	
}
